import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tree, Icon, Popconfirm } from 'antd';
import splitList from '../../utils/splitPermissions';
import _ from 'lodash';
const TreeNode = Tree.TreeNode;

const styles = {
	icon: {
		marginLeft: '1em'
	}
};

function isVersionId(id) {
	return id[0] === 'v';
}

class PermissionTree extends Component {

	componentWillReceiveProps(nextProps) {
		if (nextProps.list !== this.props.list || nextProps.list.length !== this.props.list.length) {
			this.tree = this.renderTree(nextProps.list, 0);
		}
	}

	getChildrenIds(id, list, ids = []) {
		list.forEach(p => {
			if (p.pPermissionId === id) {
				ids.push(p.id);
				if (p.versionCode) return;
				this.getChildrenIds(p.id, list, ids);
			}
		});
		return ids;
	}

	getParentIds(id, list, versionList = []) { // 添加permissionKey限制
		let target = null;
		if (isVersionId(id)) {
			const rid = parseInt(id.split('-')[1]);
			target = versionList.find(t => t.id === rid);
		} else {
			const rid = parseInt(id);
			target = list.find(t => t.id === rid && t.uri);
		}
		if (!target || !target.pPermissionId) return ['0'];
		return [target.pPermissionId].concat(this.getParentIds(target.pPermissionId, list));
	}

	getCheckedKeys(ids) {
		const { list } = this.props;
		const keys = ids.filter(id => {
			// const cid = this.getChildrenIds(parseInt(id), list);
			// return !cid.length;
			const rid = parseInt(id);
			return !list.some(p => p.pPermissionId === rid);
		});
		return keys;
	}

	select = (ids, e) => {
		const { list } = this.props;
		const checked = e.checked;
		const selId = _.get(e, 'node.props.eventKey', 0);
		const { versionList } = splitList(list);
		// 版本的id为 'v-id'; 接口权限的id为 id
		let idSet = [];
		const id = selId;
		const cids = isVersionId(id) ? [] : this.getChildrenIds(id, list).map(i => i.toString());
		const pids = ids.reduce((p, i) => {
			const tem = this.getParentIds(i, list, versionList);
			return p.concat(tem);
		}, []).map(j => j.toString());
		idSet = new Set(ids.concat(cids, pids));
		if (!checked) {
			cids.forEach(i => idSet.delete(i));
		}
		this.props.select(Array.from(idSet));
	}

	renderTitle(t, versionList) {
		const { select, edit, add } = this.props;
		if (!t) {
			return (
				<span>
					根权限
					{select ? null
						: <Icon type="plus-circle-o" style={styles.icon} onClick={() => add({ id: 0 })} />
					}
				</span>
			);
		}
		if (select) return t.permissionName || `版本号：${t.versionName}`;
		return (
			<span>
				{t.permissionName ? t.permissionName : `可选版本号：${t.versionName}`}
				{!t.versionName ? ([
					<Icon type="edit" style={styles.icon} onClick={() => edit(t, versionList)} />,
					<Popconfirm
						title="确定删除该权限吗？"
						onConfirm={() => this.props.delete(t)}
						okText="确定"
						cancelText="取消"
					>
						<Icon type="delete" style={styles.icon} />
					</Popconfirm>,
					<Icon type="plus-circle-o" style={styles.icon} onClick={() => add(t)} />
				]) : null}
			</span>
		);
	}

	renderTree(list, id) {
		const doms = [];
		list.forEach(t => {
			if (t.pPermissionId !== id) return;
			const props = {
				title: this.renderTitle(t, list.filter(v => !v.permissionKey && t.id === v.pPermissionId)),
				key: t.permissionKey ? t.id : `v-${t.id}`
			};
			// 版本权限id有可能会和接口权限一致，permissionKey===null为版本
			if (list.some(l => l.pPermissionId === t.id && t.permissionKey)) {
				props.children = this.renderTree(list, t.id);
			}
			doms.push(<TreeNode {...props} />);
		});
		return doms;
	}

	render() {
		const { list = [], select, checkedKeys = [], onDrop, isAdmin } = this.props;
		list.forEach(l => !list.some(p => p.id === l.pPermissionId) ? l.pPermissionId = 0 : null);
		if (!this.tree) {
			this.tree = this.renderTree(list, 0);
		}
		console.log(this.renderTitle())
		console.log(this.tree)
    console.log('-------')
		return (
			<Tree
				checkable={!!select}
				checkedKeys={this.getCheckedKeys(checkedKeys)}
				showLine
				defaultExpandedKeys={['0']}
				onCheck={this.select}
				draggable={isAdmin}
				onDrop={onDrop}
			>
				<TreeNode title={this.renderTitle()} key="0">
					{this.tree}
				</TreeNode>
			</Tree>
		);
	}
}

PermissionTree.propTypes = {
	edit: PropTypes.func,
	add: PropTypes.func,
	delete: PropTypes.func,
	list: PropTypes.array.isRequired,
	select: PropTypes.func,
	checkedKeys: PropTypes.array
};

export default PermissionTree;
